<template>
  <a-spin :spinning="loading">
    <a-card>
      <a-tabs>
        <a-tab-pane key="official" tab="自行添加">
          <div class="mb-20">* 搭配内商品若在伯俊未完善SKU信息，则无法创建搭配，请确保填写的款号有SKU信息</div>
          <div class="mb-20 create-flex" v-if="statusInfo && statusInfo.name">
            <div>{{ statusInfo.name }}</div>
            <a-button type="primary" @click="downLoadResult" v-if="statusInfo && statusInfo.status == 'success'">下载导入结果</a-button>
          </div>
          <div>
            <a-radio-group v-model="addType" @change="onRadioChange" class="mb-20">
              <a-radio value="single">单套搭配添加</a-radio>
              <a-radio value="batch">批量搭配添加</a-radio>
            </a-radio-group>
          </div>
          <a-row v-if="addType == 'single'">
            <a-col :span="24">
              <h4 style="padding: 10px 0">单套搭配添加</h4>
              <a-form :form="form" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
                <a-form-item label="主款SKC">
                  <a-input
                    placeholder="请输入SKC编码"
                    v-decorator="[
                      'productNoMain',
                      {
                        rules: [
                          {
                            required: true,
                            message: '请输入SKC编码'
                          }
                        ]
                      }
                    ]"
                  ></a-input>
                </a-form-item>
                <div>
                  <a-form-item  v-for="(item, index) in fileds" :key="index" :label="`搭配款${index + 1}-SKC`">
                    <a-input
                      placeholder="请输入SKC编码"
                      v-decorator="[
                        `sorting-${index + 1}`,
                        {
                          validateTrigger: ['change', 'blur'],
                          rules: [
                            {
                              required: true,
                              whitespace: true,
                              message: '请输入SKC编码'
                            }
                          ]
                        }
                      ]"
                    ></a-input>
                    <a-icon v-if="index > 0" class="dynamic-delete-button mt-10" type="minus-circle-o" @click="() => remove(index)" />
                  </a-form-item>
                </div>
                <a-row v-if="fileds.length < 6" style="margin-bottom: 20px">
                  <a-col :md="{ span: 6, offset: 4 }" :lg="{ span: 6, offset: 3 }" class="info-action">
                    <a-button style="padding: 0" type="link" @click="add"> +添加搭配款商品</a-button>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :md="{ span: 6, offset: 4 }" :lg="{ span: 6, offset: 3 }" class="info-action">
                    <a-button type="primary" @click="next">下一步</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
          </a-row>
          <a-row v-else>
            <a-col :span="12">
              <a-row type="flex" justify="start" align="middle" class="mb-20">
                <a-col :span="5">
                  <h4>批量搭配添加</h4>
                </a-col>
                <a-col :span="5">
                  <a-button type="link" @click="downTemplate">下载导入模板</a-button>
                </a-col>
              </a-row>
              <a-row class="mb-20">
                <a-col :span="24">
                  <a-upload :disabled="statusInfo.status == 'wait'" :fileList="fileList" :beforeUpload="beforeUploadHandle" :remove="removeFile">
                    <a-button> <a-icon type="upload" /> 上传表格 </a-button>
                  </a-upload>
                </a-col>
              </a-row>
              <a-button type="primary" class="mb-20" @click="complate">完成</a-button>
              <div style="padding-bottom: 10px">* 批量导入搭配后，需要完善搭配信息后才生效</div>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </a-spin>
</template>
<script>
import AddFromLook from '../components/AddFromLook'
import { createCollocation, importUrl, importJudge, downLoadOfficeTmplate, gettest, iprotantState, downloadResults } from '@/api/micromall/collocation.js'
import { queryResult } from '@/api/micromall/box.js'
import { uploadAction } from '@/api/manage.js'
export default {
  components: { AddFromLook },
  data() {
    return {
      addType: 'single',
      importJudge,
      importUrl,
      index: 1,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
          md: { span: 4 },
          lg: { span: 3 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
          md: { span: 6 },
          lg: { span: 6 }
        }
      },
      form: this.$form.createForm(this, { name: 'collocation' }),
      fileds: [
        {
          key: 'default'
        }
      ],
      fileList: [],
      loopTimer: null,
      loading: false,
      statusInfo:null
    }
  },
  mounted() {
    this.queryStatus()
  },
  beforeDestroy() {
    if(this.loopTimer){
      clearInterval(this.loopTimer)
      this.loopTimer = null
    }
  },
  methods: {
    downLoadResult(){
      window.open(downloadResults)
    },
    async queryStatus(){
      const res = await iprotantState()
      if(res.code ==200){
        this.statusInfo = res.data
      }
      console.log(res)
    },
    removeFile(e) {
      this.fileList = []
    },
    async loopResult(key) {
      const result = await queryResult({ key })
      if (result.data !== 'wait') {
        this.loading = false
        this.showLoading = false
        clearInterval(this.loopTimer)
        this.loopTimer = null
        if (result.data === '导入成功') {
          this.$router.push({ path: '/micromall/marketing/collocation/official', query: { type: 1 } })
        }
      }
    },
    async upload(formData) {
      this.loading = true
      const response = await uploadAction(importUrl, formData)
      this.loading = false
      if(response.code == 200){
        this.$message.success('导入任务已创建，请耐心等待导入结果')
        this.fileList = []
        this.queryStatus()
      }else{
        this.$message.error(response.msg)
      }
    },
    async complate() {
      if(this.statusInfo.status == 'wait'){
        return this.$message.error('已有导入任务进行中，请稍后再试')
      }
      const [file] = this.fileList
      if (!file) {
        return this.$message.error('请选择表格')
      }
      const formData = new FormData()
      formData.append('file', file)
      this.upload(formData)
      // const re = await uploadAction(importJudge, formData)
      // if (re.code == 200) {
      //   re.data != '' ? this.showConfrim(re.data, formData) : this.upload(formData)
      // } else {
      //   this.$message.error(re.msg)
      // }
    },
    showConfrim(text = '', formData) {
      let that = this
      return new Promise(async (resolve, reject) => {
        this.$confirm({
          content: `表格第${text}行SKC数据有误，请核对后重新导入。点击继续导入，将导入表格中数据无误的搭配`,
          okText:"确认导入",
          cancelText:"取消导入",
          onOk() {
            that.upload(formData)
          },
          onCancel() {}
        })
      })
    },
    beforeUploadHandle(file) {
      const { name } = file;
      const isExcel = /(xls|xlsx)$/i.test(name);
      if (!isExcel) {
        this.$message.error('请上传excel表格');
        return false
      }
      this.fileList = [file]
      return false
    },
    downTemplate() {
      const url = downLoadOfficeTmplate
      window.open(url)
    },
    // 移除动态新增的元素
    remove(index) {
      let { fileds } = this
      fileds.splice(index, 1)
      this.fileds = fileds
    },
    // 新增元素
    add() {
      const obj = { key: '' }
      let { fileds } = this
      fileds.push(obj)
      this.fileds = fileds
    },
    // "productAttrIdMain":"1353157",
    //   "labelNameId":"1,2",
    //   "saveCollocationModelDtoList":[
    //       {
    //           "productNoModel":"5J8311610",
    //           "sorting":"1",
    //           "productAttrIdModel":"1355695"
    //       },
    next(e) {
      e.preventDefault()
      const { addType } = this
      if (addType == 'single') {
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log(values)
            let params = {
              productNoMain: values.productNoMain,
              saveCollocationModelDtoList: []
            }
            for (const key in values) {
              if (key.indexOf('sorting') == 0) {
                const index = key.split('-')[1]
                let obj = {
                  sorting: index,
                  productNoModel: values[key]
                }
                params.saveCollocationModelDtoList.push(obj)
              }
            }
            console.log(params)
            this.validateStyleNo(params)
          }
        })
      }
      if (this.$route.query.type == 'official') {
      }
    },
    async validateStyleNo(values) {
      const re = await createCollocation(values)
      if (re.code == 200 && re.data) {
        this.$router.replace({
          path: `/micromall/marketing/collocation/edit`,
          query: {
            id: re.data,
            type: 'official'
          }
        })
      } else {
        this.$error({
          content: `${re.msg}`
        })
      }
      console.log(re)
    },
    onRadioChange(e) {
      this.addType = e.target.value
    }
  }
}
</script>
<style scoped>
.mt-10 {
  margin-top: -10px;
}
.create-flex{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 200px;
}
.mb-20 {
  margin-bottom: 20px;
}
.dynamic-delete-button {
  cursor: pointer;
  position: absolute;
  right: -30px;
  top: 8px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>

